#include <vector>
#include <unordered_map>
#include <string>
#include <algorithm>
#include <stack>
#include <queue>
using namespace std;

class Node {
public:
    int val;
    Node* left;
    Node* right;
    Node* next;

    Node() : val(0), left(NULL), right(NULL), next(NULL) {}

    Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {}

    Node(int _val, Node* _left, Node* _right, Node* _next)
        : val(_val), left(_left), right(_right), next(_next) {}
};


class Solution {
public:
    Node* connect(Node* root) {
        if (!root) return nullptr; 
        queue<Node*> q;
        q.push(root);
        while(!q.empty())
        {
            int size = q.size();
            for(int i=0;i<size;i++)
            {
                Node* front = q.front();
                q.pop();
                
                // 只在非最后一个节点时才指向队列头（下一个节点）
                if(i < size - 1) {
                    front->next = q.front();
                } else {
                    front->next = nullptr; // 最后一个节点next为null
                }

                if(front->left)
                    q.push(front->left);
                if(front->right)
                    q.push(front->right);
            }
        }
        return root;
    }
};